package com.holike.crm.activity.report;

import android.content.Context;
import android.graphics.Paint;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gallopmark.recycler.adapterhelper.CommonAdapter;
import com.gallopmark.recycler.decorationhepler.LinearItemDecoration;

import io.reactivex.disposables.Disposable;
import pony.xcode.tablayout.CommonTabLayout;
import pony.xcode.tablayout.TabEntity;
import pony.xcode.tablayout.CustomTabEntity;
import pony.xcode.tablayout.OnTabSelectListener;

import com.holike.crm.R;
import com.holike.crm.base.ActivityHelper;
import com.holike.crm.base.BaseActivity;
import com.holike.crm.bean.BusinessObjectivesBean;
import com.holike.crm.fragment.report.target.BusinessTargetFragment;
import com.holike.crm.fragment.report.target.EmployeeTargetFragment;
import com.holike.crm.rxbus.MessageEvent;
import com.holike.crm.rxbus.RxBus;
import com.holike.crm.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pony on 2019/10/30.
 * Version v3.0 app报表
 * 经营目标
 */
class BusinessTargetHelper extends ActivityHelper {
    private Callback mCallback;
    private FrameLayout mContainer;
    private FragmentManager mFragmentManager;
    private Fragment mShowingFragment;
    private static final String TAG_SHOP = "tag-shop";
    private static final String TAG_PERSON = "tag-person";
    private int mCurrentTab = 0;
    private boolean mRefresh;
    private Disposable mDisposable;

    BusinessTargetHelper(BaseActivity<?, ?> activity, Callback callback) {
        super(activity);
        this.mCallback = callback;
        mContainer = obtainView(R.id.fl_fragment_main);
        mFragmentManager = mActivity.getSupportFragmentManager();
        doRequest();
        mDisposable = RxBus.getInstance().toObservable(MessageEvent.class).subscribe(event -> {
                    mRefresh = true;
                    doRequest();
                }
        );
    }

    void doRequest() {
        mCallback.doRequest("");
    }

    void onSuccess(BusinessObjectivesBean bean) {
        if (TextUtils.equals(bean.type, "1")) { //展示经营目标
            mActivity.setTitle(R.string.business_target);
            mActivity.setRightMenu(R.string.title_set_target, view -> mActivity.startActivity(BusinessSetTargetActivity.class));
            updateBusiness(bean);
        } else if (TextUtils.equals(bean.type, "2")) { //展示个人目标
            mActivity.setTitle(R.string.personal_target);
            updatePersonal(bean);
        } else {  //其他情况展示缺省页
            mContainer.removeAllViews();
            LayoutInflater.from(mActivity).inflate(R.layout.include_empty_textview, mContainer, true);
        }
        mRefresh = false;
    }

    /*经营目标*/
    private void updateBusiness(BusinessObjectivesBean bean) {
        if (!mRefresh) {
            mContainer.removeAllViews();
            View contentView = LayoutInflater.from(mActivity).inflate(R.layout.include_business_objectives, mContainer, true);
            requestUpdate(contentView, bean);
        } else {
            requestUpdate(mContainer.findViewById(R.id.ll_content_layout), bean);
            requestFragmentUpdate(bean);
        }
    }

    private void requestUpdate(View contentView, BusinessObjectivesBean bean) {
        if (contentView == null) return;
        ((TextView) contentView.findViewById(R.id.tv_time_detail)).setText(bean.time);
        String target = mActivity.getString(R.string.tips_transaction_target);
        if (!TextUtils.isEmpty(bean.moneyTotal)) {
            target += bean.moneyTotal;
        }
        ((TextView) contentView.findViewById(R.id.tv_target_performance)).setText(target);
        String finish = mActivity.getString(R.string.tips_transaction_completion);
        if (!TextUtils.isEmpty(bean.countTotal)) {
            finish += bean.countTotal;
        }
        ((TextView) contentView.findViewById(R.id.tv_finish_performance)).setText(finish);
        LinearLayout progressLayout = contentView.findViewById(R.id.ll_progress_layout);
        int maxWidth = DensityUtil.getWindowWidth(mActivity) - progressLayout.getPaddingLeft() - progressLayout.getPaddingRight();
        ((TextView) contentView.findViewById(R.id.tv_percent)).setText(bean.getPercent());
        TextView tvPercent = contentView.findViewById(R.id.tv_percent);
        LinearLayout.LayoutParams tlp = (LinearLayout.LayoutParams) tvPercent.getLayoutParams();
        tlp.leftMargin = getLeftMargin(bean.getPercentValue(), getTextWidth(bean.getPercent(), tvPercent.getPaint()), maxWidth);
        View vProgress = contentView.findViewById(R.id.v_progress);
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) vProgress.getLayoutParams();
        lp.width = getProgressWidth(bean.getPercentValue(), maxWidth);
        vProgress.setLayoutParams(lp);
        List<CustomTabEntity> tabEntities = new ArrayList<>();
        final List<String> tagList = new ArrayList<>();
        if (bean.isShop()) {  //经营目标
            tabEntities.add(new TabEntity(mActivity.getString(R.string.business_target)));
            tagList.add(TAG_SHOP);
        }
        if (bean.isPerson()) {
            tabEntities.add(new TabEntity(mActivity.getString(R.string.employee_target)));
            tagList.add(TAG_PERSON);
        }
        if (tabEntities.isEmpty()) {
            FrameLayout flContainer = obtainView(R.id.fl_container);
            flContainer.removeAllViews();
            LayoutInflater.from(mActivity).inflate(R.layout.include_empty_textview, flContainer, true);
        } else {
            LinearLayout contentLayout = obtainView(R.id.ll_content_layout);
            if (contentLayout.getChildCount() > 2) {
                contentLayout.removeViewAt(1);
            }
            if (tabEntities.size() > 1) {
                View view = LayoutInflater.from(mActivity).inflate(R.layout.include_common_tablayout, contentLayout, false);
                CommonTabLayout tabLayout = view.findViewById(R.id.tab_layout);
                tabLayout.setTabData(tabEntities);
                tabLayout.setCurrentTab(mCurrentTab);
                tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
                    @Override
                    public void onTabSelect(int position) {
                        mCurrentTab = position;
                        setCurrentTab(bean, tagList.get(position));
                    }

                    @Override
                    public void onTabReselect(int position) {

                    }
                });
                contentLayout.addView(view, 1);
            }
            if (!mRefresh) {
                setCurrentTab(bean, tagList.get(0));
            }
        }
    }

    private void setCurrentTab(BusinessObjectivesBean bean, String tag) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (mShowingFragment != null) {
            transaction.hide(mShowingFragment);
        }
        Fragment fragment = mFragmentManager.findFragmentByTag(tag);
        if (fragment != null) {
            transaction.show(fragment);
        } else {
            if (TextUtils.equals(tag, TAG_SHOP)) {
                fragment = BusinessTargetFragment.newInstance(bean);
            } else {
                fragment = EmployeeTargetFragment.newInstance(bean);
            }
            transaction.add(R.id.fl_container, fragment, tag);
        }
        mShowingFragment = fragment;
        transaction.commitAllowingStateLoss();
    }

    private void requestFragmentUpdate(BusinessObjectivesBean bean) {
        Fragment businessFragment = mFragmentManager.findFragmentByTag(TAG_SHOP);
        if (businessFragment != null) {
            ((BusinessTargetFragment) businessFragment).requestUpdate(bean);
        }
        Fragment employeeFragment = mFragmentManager.findFragmentByTag(TAG_PERSON);
        if (employeeFragment != null) {
            ((EmployeeTargetFragment) employeeFragment).requestUpdate(bean);
        }
    }

    /*个人目标*/
    private void updatePersonal(BusinessObjectivesBean bean) {
        mContainer.removeAllViews();
        View view = LayoutInflater.from(mActivity).inflate(R.layout.include_personal_target, mContainer, true);
        ((TextView) view.findViewById(R.id.tv_time_detail)).setText(bean.time);
        List<BusinessObjectivesBean.PersonDataBean> dataList = bean.getPersonData();
        FrameLayout frameLayout = view.findViewById(R.id.fl_personal_container);
        if (dataList.isEmpty()) {
            View emptyView = LayoutInflater.from(mActivity).inflate(R.layout.include_empty_textview, frameLayout, true);
            ((TextView) emptyView.findViewById(R.id.tv_empty)).setText(mActivity.getString(R.string.tips_empty_target));
        } else {
            RecyclerView recyclerView = new RecyclerView(mActivity);
            recyclerView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            recyclerView.setClipToPadding(false);
            recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
            final int dp10 = mActivity.getResources().getDimensionPixelSize(R.dimen.dp_10);
            recyclerView.setPadding(dp10, 0, dp10, mActivity.getResources().getDimensionPixelSize(R.dimen.dp_20));
            recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
            recyclerView.addItemDecoration(new LinearItemDecoration(RecyclerView.VERTICAL, dp10, ContextCompat.getColor(mActivity, R.color.bg_transparent)));
            List<InnerBean> data = new ArrayList<>();
            for (BusinessObjectivesBean.PersonDataBean dataBean : dataList) {
                //1 新建客户数、2预约量尺数、3业绩（万）、4回款（万）、5量尺数、6出图数、7下单（万）
                if (TextUtils.equals(dataBean.type, "1")) { //新建客户数
                    data.add(new InnerBean(getTitle(R.string.number_of_new_customers, R.string.slanting_rod_count),
                            getTargetOrPerformance(R.string.tips_new_customer_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_new_customer_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col1));
                } else if (TextUtils.equals(dataBean.type, "2")) { //2预约量尺数
                    data.add(new InnerBean(getTitle(R.string.number_of_reservation_scale, R.string.slanting_rod_count),
                            getTargetOrPerformance(R.string.tips_appointment_gauge_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_appointment_gauge_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col2));
                } else if (TextUtils.equals(dataBean.type, "3")) { //3业绩（万）
                    data.add(new InnerBean(getTitle(R.string.transaction, R.string.slanting_rod_million),
                            getTargetOrPerformance(R.string.tips_transaction_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_transaction_completion, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col5));
                } else if (TextUtils.equals(dataBean.type, "4")) { //4回款（万）
                    data.add(new InnerBean(getTitle(R.string.payback, R.string.slanting_rod_million),
                            getTargetOrPerformance(R.string.tips_payback_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_payback_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col6));
                } else if (TextUtils.equals(dataBean.type, "5")) { //5量尺数
                    data.add(new InnerBean(getTitle(R.string.number_of_measuring, R.string.slanting_rod_count),
                            getTargetOrPerformance(R.string.tips_gauge_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_gauge_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col3));
                } else if (TextUtils.equals(dataBean.type, "6")) { //6出图数
                    data.add(new InnerBean(getTitle(R.string.number_of_output_graphs, R.string.slanting_rod_count),
                            getTargetOrPerformance(R.string.tips_drawing_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_drawing_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col4));
                } else if (TextUtils.equals(dataBean.type, "7")) {
                    data.add(new InnerBean(getTitle(R.string.order, R.string.slanting_rod_million),
                            getTargetOrPerformance(R.string.tips_order_target, dataBean.getTarget()),
                            getTargetOrPerformance(R.string.tips_order_completed, dataBean.getCount()),
                            dataBean.getPercent(), dataBean.getPercentValue(), R.drawable.shape_progressbar_progress_col7));
                }
            }
            recyclerView.setAdapter(new PersonalDataAdapter(mActivity, data, dp10));
            frameLayout.addView(recyclerView);
        }
    }

    private CharSequence getTitle(int origin, int content) {
        String source = mActivity.getString(origin);
        int start = source.length();
        source += mActivity.getString(content);
        SpannableString ss = new SpannableString(source);
        ss.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.textColor8)), start, source.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    private CharSequence getTargetOrPerformance(int origin, String content) {
        String source = mActivity.getString(origin);
        int start = source.length();
        source += (TextUtils.isEmpty(content) ? "" : content);
        SpannableString ss = new SpannableString(source);
        ss.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mActivity, R.color.textColor4)), start, source.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    private final class InnerBean {
        CharSequence title;
        CharSequence target;
        CharSequence performance;
        String percent;
        double progress;
        int progressResource;

        InnerBean(CharSequence title, CharSequence target, CharSequence performance,
                  String percent, double progress, int progressResource) {
            this.title = title;
            this.target = target;
            this.performance = performance;
            this.percent = percent;
            this.progress = progress;
            this.progressResource = progressResource;
        }
    }

    private int getTextWidth(String text, Paint paint) {
        if (TextUtils.isEmpty(text)) return 0;
        return (int) Math.ceil(paint.measureText(text)); //向上取整
    }

    private int getLeftMargin(double progress, int textWidth, int maxWidth) {
        int width = (int) Math.round(progress * maxWidth); //四舍五入取整
        if (width > maxWidth) {
            width = maxWidth;
        }
        if (width > textWidth) {
            return (width - textWidth);
        }
        return 0;
    }

    private int getProgressWidth(double progress, int maxWidth) {
        int width = (int) Math.round(progress * maxWidth); //四舍五入取整
        return width > maxWidth ? maxWidth : width;
    }

    private final class PersonalDataAdapter extends CommonAdapter<InnerBean> {
        private int mMaxWidth;

        PersonalDataAdapter(Context context, List<InnerBean> dataList, int dimenOf) {
            super(context, dataList);
            mMaxWidth = DensityUtil.getScreenWidth(mContext) - dimenOf * 4;
        }

        @Override
        protected int bindView(int viewType) {
            return R.layout.item_personal_target;
        }

        @Override
        public void onBindHolder(RecyclerHolder holder, InnerBean bean, int position) {
            holder.setText(R.id.tv_title, bean.title);
            holder.setText(R.id.tv_target, bean.target);
            holder.setText(R.id.tv_performance, bean.performance);
            View vProgress = holder.obtainView(R.id.v_progress);
            TextView tvPercent = holder.obtainView(R.id.tv_percent);
            LinearLayout.LayoutParams tlp = (LinearLayout.LayoutParams) tvPercent.getLayoutParams();
            tlp.leftMargin = getLeftMargin(bean.progress, getTextWidth(bean.percent, tvPercent.getPaint()), mMaxWidth);
            tvPercent.setLayoutParams(tlp);
            tvPercent.setText(bean.percent);
            FrameLayout.LayoutParams vlp = (FrameLayout.LayoutParams) vProgress.getLayoutParams();
            vlp.width = getProgressWidth(bean.progress, mMaxWidth);
            vProgress.setLayoutParams(vlp);
            vProgress.setBackgroundResource(bean.progressResource);
        }
    }

    void onFailure(String failReason) {
        mContainer.removeAllViews();
        LayoutInflater.from(mActivity).inflate(R.layout.include_empty_page, mContainer, true);
        mActivity.noNetwork(failReason);
    }

    void destroy() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    interface Callback {
        void doRequest(String shopId);
    }
}
